package com.yuerlive.rainbow.base;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.UiThread;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.androidadvance.topsnackbar.TSnackbar;
import com.umeng.analytics.MobclickAgent;
import com.yuerlive.rainbow.R;
import com.yuerlive.rainbow.common.ActivityStack;
import com.yuerlive.rainbow.common.NetBroadcastReceiver;
import com.yuerlive.rainbow.module.login.LoginWayActivity;
import com.yuerlive.rainbow.module.main.StartActivity;
import com.yuerlive.rainbow.utils.DeviceUtils;
import com.yuerlive.rainbow.utils.L;
import com.yuerlive.rainbow.utils.NetUtil;
import com.yuerlive.rainbow.utils.ToastUtils;
import com.yuerlive.rainbow.widget.CustomDialog;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by xiaoyi on 2017/5/17.
 */

public abstract class BaseActivity<T extends BasePresenter> extends MPermissionsActivity implements NetBroadcastReceiver.NetEventHandler {
    @Nullable
    @BindView(R.id.statusBar)
    View statusBar;
    @Nullable
    @BindView(R.id.headerBack)
    ImageView headBack;
    @Nullable
    @BindView(R.id.headerTitle)
    TextView headerTitle;

    public T presenter;

    CustomDialog logoutDialog;

    protected abstract int getLayoutId();

    protected abstract void initViews();

    protected String TAG = getClass().getSimpleName();

    private Unbinder unbinder;

    public Activity mActivity;
    private NetBroadcastReceiver myReceiver;
    /**
     * 网络类型
     */
    private int netMobile;
    private TSnackbar snackbar;


    @Override
    protected final void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(getLayoutId());
        if (!(this instanceof StartActivity)){
            getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        }
        mActivity = this;
        unbinder = ButterKnife.bind(this);
        NetBroadcastReceiver.addListener(this);
        init();
        inspectNet();
        initViews();
        registerReceiver();
        ActivityStack.add(this);
    }

    private void registerReceiver() {
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        myReceiver = new NetBroadcastReceiver();
        this.registerReceiver(myReceiver, filter);
    }

    private void init() {
        setStatus();
        if (headBack != null)
            headBack.setOnClickListener(v -> onBackPressed());
    }

    /*标题*/
    protected void setTitle(String title) {
        if (headerTitle != null) {
            headerTitle.setText(title);
        }
    }

    /*状态栏view*/
    private void setStatus() {
        if (statusBar == null || Build.VERSION.SDK_INT < 21) return;
        ViewGroup.LayoutParams params = statusBar.getLayoutParams();
        params.height = DeviceUtils.deviceStatusHeight(mActivity);
        statusBar.setLayoutParams(params);
        setTranslucentStatus(true);
    }

    protected void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    @Override
    protected void onDestroy() {
        dismissSnackBar();
        releasePresenter();
        NetBroadcastReceiver.removeListener(this);
        this.unregisterReceiver(myReceiver);
        unbinder.unbind();
        if (logoutDialog != null) logoutDialog.dismiss();
        ActivityStack.remove(this);
        super.onDestroy();
    }

    private void releasePresenter() {
        if (presenter != null) {
            presenter.unSubscribe();
        }
    }

    public void jumpToActivity(@NonNull Class clazz) {
        jumpToActivity(clazz, null);
    }

    protected void jumpToActivity(@NonNull Class clazz, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, clazz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
        // this.overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    protected void jumpToActivity(@NonNull Intent intent) {
        startActivity(intent);
        //this.overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    protected void jumpToActivityForResult(@Nullable Class clazz, int requestCode) {
        jumpToActivityForResult(clazz, requestCode, null);
    }

    protected void jumpToActivityForResult(@Nullable Intent intent, int requestCode) {
        startActivityForResult(intent, requestCode);
    }

    protected void jumpToActivityForResult(@Nullable Class clazz, int requestCode, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, clazz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
        //this.overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    @UiThread
    protected void showToast(int resId) {
        ToastUtils.show(resId);
    }

    @UiThread
    protected void showToast(String msg) {
        ToastUtils.show(msg);
    }

    @UiThread
    protected void showToast(String msg, int duration) {
        ToastUtils.show(msg, duration);
    }

    @UiThread
    protected void showToast(int resId, int duration) {
        ToastUtils.show(resId, duration);
    }

    /**
     * @param view     依附的View
     * @param tips     提示语
     * @param showType 0 短时间显示 1 永久显示（没有网络的时候）
     */
    @UiThread
    public void showSnackbar(View view, String tips, int showType) {
        L.e(TAG, "showType" + showType);
        snackbar = TSnackbar
                .make(view, tips, TSnackbar.LENGTH_SHORT);
        View snackbarView = snackbar.getView();
        snackbarView.setBackgroundColor(mActivity.getResources().getColor(R.color.login_out_color));
        snackbarView.setMinimumHeight(DeviceUtils.dp2px(mActivity, 73));
        TextView tv = (TextView) snackbarView.findViewById(R.id.snackbar_text);
        tv.setTextColor(this.getResources().getColor(R.color.white));
        tv.setGravity(Gravity.CENTER);
        if (showType == 0) {
            snackbar.show();
        } else if (showType == 1) {
            snackbar.setDuration(TSnackbar.LENGTH_INDEFINITE);
            snackbar.show();
        }
    }

    @UiThread
    protected void dismissSnackBar() {
        if (snackbar != null && snackbar.isShown()) {
            snackbar.dismiss();
        }
    }

    @Override
    public void onNetChange(int netWorkState) {
        netMobile = netWorkState;
        if (netWorkState == 0) {
            showSnackbar(getRootView(mActivity), "网络异常", 1);
        } else {
            dismissSnackBar();
        }
        isNetConnect();
    }

    public static View getRootView(Activity context) {
        return ((ViewGroup) context.findViewById(android.R.id.content)).getChildAt(0);
    }

    /**
     * 判断有无网络 。
     *
     * @return true 有网, false 没有网络.
     */
    public boolean isNetConnect() {
        if (netMobile == 1) {
            return true;
        } else if (netMobile == 2) {
            return true;
        } else if (netMobile == 0) {
            return false;
        }
        return false;
    }

    public boolean inspectNet() {
        this.netMobile = NetUtil.getNetworkState(mActivity);
        return isNetConnect();
    }

    public void showLogoutDialog() {
        if (logoutDialog == null) {
            View logoutView = LayoutInflater.from(this)
                    .inflate(R.layout.layout_choose_dialog, null);
            logoutDialog = new CustomDialog(this, logoutView);
            TextView tvTitle = (TextView) logoutView.findViewById(R.id.tvTitle);
            tvTitle.setText("下线提醒");
            TextView tvContent = (TextView) logoutView.findViewById(R.id.tvContent);
            tvContent.setText("检测到您的账号在其他设备登录，您已被强制下线，请重新登录");
            logoutView.findViewById(R.id.btnCancel).setVisibility(View.GONE);
            TextView tvSure = (TextView) logoutView.findViewById(R.id.btnSure);
            tvSure.setText("重新登录");
            tvSure.setOnClickListener((v) -> {
                jumpToActivity(LoginWayActivity.class);
                logoutDialog.dismiss();
            });
            logoutDialog.setCancelable(false);
            logoutDialog.setCanceledOnTouchOutside(false);
        } else {
            logoutDialog.show();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
}
